/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package frontController;

import businessDelegates.PautaBusinessDelegate;
import businessObjects.Cliente;
import businessObjects.Pauta;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author rene
 */
@WebServlet(name="insertarPauta", urlPatterns={"/insertarPauta"})
public class insertarPauta extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        String action = request.getParameter("action");
        HttpSession currentSession = request.getSession();        
        if(currentSession == null || !currentSession.getAttribute("rol").equals("cliente")){
            response.sendRedirect("index.jsp");
        }else{
            if(action == null){
                currentSession.setAttribute("error", "Ha ocurrido un error al intentar crear la pauta. Por favor intente nuevamente.");
                response.sendRedirect("error.jsp");
            }else{
                if(action.equals("pautaNew")){
                    Pauta p = new Pauta();
                    int estado = 1;
                    String esq = request.getParameter("Tipo");
                    int esquema = 1;
                    String url = "";
                    if(esq.equals("basica")){
                        esquema = 1;
                    }else if(esq.equals("premium")){
                        esquema = 2;
                        url = request.getParameter("url");
                    }
                    String fecha1 = request.getParameter("fecha1");
                    String fecha2 = request.getParameter("fecha2");
                    Date fechaInicio = new Date();
                    String [] fechai = fecha1.split("/");
                    fechaInicio.setDate(Integer.parseInt(fechai[1]));
                    fechaInicio.setMonth(Integer.parseInt(fechai[0])-1);
                    int year1 = Integer.parseInt(fechai[2])-1900;
                    fechaInicio.setYear(year1);
                    Date fechaFin = new Date();
                    String [] fechaf = fecha2.split("/");
                    fechaFin.setDate(Integer.parseInt(fechaf[1]));
                    fechaFin.setMonth(Integer.parseInt(fechaf[0])-1);
                    int year2 = Integer.parseInt(fechaf[2])-1900;
                    fechaFin.setYear(year2);
                    String bannerloc = request.getParameter("bannerurl");
                    PautaBusinessDelegate pbd = new PautaBusinessDelegate();                
                    try{
                        p.setClicks(0);
                        p.setIdEstado(pbd.findEstado(estado));
                        p.setLoginCliente((Cliente)currentSession.getAttribute("usuario"));
                        p.setIdEsquema(pbd.findEsquema(esquema));
                        p.setFechaFin(fechaInicio);
                        p.setFechaInicio(fechaFin);                        
                        p.setUrl(url);
                        p.setBanner(bannerloc);
                        }catch(Exception e){
                            currentSession.setAttribute("message", "Registro fallido procesando datos");
                        }                        
                        int dias = (int) ((fechaFin.getTime() - fechaInicio.getTime())/(100*60*60*24));
                        int costo = (int) (pbd.findEsquema(esquema).getCostoDiario() * dias);
                        currentSession.setAttribute("days",dias);
                        currentSession.setAttribute("totalAmount", costo);
                        currentSession.setAttribute("pauta", p);
                        response.sendRedirect("cliente/billinginfo.jsp");
                    }
                else if(action.equals("pagar")){
                    Pauta a = (Pauta) currentSession.getAttribute("pauta");
                    PautaBusinessDelegate pbd = new PautaBusinessDelegate();
                    pbd.guardarPauta(a);
                    currentSession.setAttribute("resultado", "Compra exitosa");
                    response.sendRedirect("cliente/menucliente.jsp");
                }
               }
            }
        
        //response.setContentType("text/html;charset=UTF-8");
        //PrintWriter out = response.getWriter();
        //try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet insertarPauta</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet insertarPauta at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
            */
        //} finally {
        //    out.close();
        //}
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}